<template>
  <div id="viewQuestionView">
    <!-- 添加超时提示弹窗 -->
    <div v-if="showTimeoutDialog" class="timeout-modal">
      <div class="modal-content">
        <div class="icon-wrapper">
          <div class="clock-icon"></div>
        </div>
        <h2>比赛时间已结束！</h2>
        <p>正在跳转到完成页面...</p>
      </div>
    </div>
    <!-- 新增返回按钮 -->
    <div class="back-btn" @click="handleBack">
      <icon-arrow-left class="arrow-icon" />
    </div>

    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="formData" :title="formData.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ formData.timeLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ formData.memoryLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ formData.stackLimit ?? 0 }}
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="formData.content || ''" />
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code as string"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider :size="0" />
        <div class="countdown" :class="{ warning: timeLeft <= 60 }">
          {{ formattedTime }}
        </div>
        <a-button
          type="primary"
          style="min-width: 200px; margin-left: 50px"
          @click="handleSubmitClick"
        >
          提交代码
        </a-button>
      </a-col>
    </a-row>
    <!-- 在原有模板中添加提交确认弹窗 -->
    <div v-if="showSubmitDialog" class="submit-confirm-modal">
      <div class="modal-content">
        <div class="warning-icon">⚠️</div>
        <h3>确认提交代码</h3>
        <p>确定要提交代码吗？提交之后不保留原代码，请做好备份哦</p>
        <div class="button-group">
          <button class="confirm-btn" @click="doSubmit">
            我已经备份好了，确认提交
          </button>
          <button class="cancel-btn" @click="showSubmitDialog = false">
            再等等
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
  reactive,
  watch,
  withDefaults,
  defineProps,
  computed,
} from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionSubmitAddRequest,
  // QuestionSubmitControllerService,
  QuestionVO,
} from "../../../generatedQue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import MdEditor from "@/components/MdEditor.vue";
import { IconMessage } from "@arco-design/web-vue/es/icon";
import { CompetitionControllerService } from "../../../generatedCom/services/CompetitionControllerService";
import { CommentVO } from "../../../generated/models/CommentVO";
import CommentItem from "@/components/CommentItem.vue";
import {
  IconHeart,
  IconHeartFill,
  IconArrowLeft,
} from "@arco-design/web-vue/es/icon";
import { CompetitionQuestionDetailVO } from "../../../generatedCom/models/CompetitionQuestionDetailVO";
import { useRouter } from "vue-router";

// 定义各语言对应的代码模板
const languageTemplates: Record<string, string> = {
  java: `public class Main
{
    public static void main(String args[])
    {
        /**
        输入示例：
        int a = Integer.parseInt(args[0]);
        */
    }
}`,
  cpp: `#include <iostream>  
#include <string> // 包含这个头文件以使用 std::stoi  
using namespace std;  

int main(int argc, char* argv[]) {  
    // 转换命令行参数为整数  
    /**
    示例：接收参数
    int nums1 = stoi(argv[1]);  
    int nums2 = stoi(argv[2]);  
    注意，示例答案输入输出有没有换行哦
    */
    return 0;  
}`,
  go: `package main

import "fmt"

func main() {
    // 请在此输入代码
    fmt.Println("Hello, World!")
}`,
  html: `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML Template</title>
</head>
<body>
    <!-- 请在此输入代码 -->
</body>
</html>`,
};
const router = useRouter();

const question = ref<QuestionVO>();
const formData = ref<CompetitionQuestionDetailVO>();
const loadData = async () => {
  const id = router.currentRoute.value.params.id;
  const res = await CompetitionControllerService.getQuestionDetailUsingPost({
    id: Number(id),
  });
  if (res.code === 0) {
    console.log(res);
    formData.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code: languageTemplates["java"],
});
// 添加监听，当 language 改变时更新 code
watch(
  () => form.value.language,
  (newLanguage, oldLanguage) => {
    if (newLanguage !== oldLanguage) {
      form.value.code = languageTemplates[newLanguage];
      console.log("language变化：", newLanguage, "->", oldLanguage);
      console.log("form.value.code变化：", form.value.code);
    }
  }
);
// 新增响应式变量
const showSubmitDialog = ref(false);

// 修改提交方法
const handleSubmitClick = () => {
  showSubmitDialog.value = true;
};
/**
 * 提交代码
 */
const doSubmit = async () => {
  const res =
    await CompetitionControllerService.doSubmitCompetitionQuestionUsingPost({
      ...form.value,
      questionId: formData.value?.id,
    });
  if (res.code === 0) {
    message.success("提交成功");
    showSubmitDialog.value = false;
    router.go(-1); // 返回上一页
  } else {
    message.error("提交失败," + res.message);
  }
};
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const changeCode = (value: string) => {
  form.value.code = value;
};
// 新增倒计时相关逻辑
import { onUnmounted } from "vue";

const timeLeft = ref(0);
// 修改后
let timer: ReturnType<typeof setInterval> | null = null;
// 新增响应式变量
const showTimeoutDialog = ref(false);

// 修改倒计时逻辑
const startTimer = () => {
  if (timer) clearInterval(timer);
  timer = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      clearInterval(timer!);
      doSubmit();
      showTimeoutDialog.value = true; // 显示弹窗
      setTimeout(() => {
        router.push("/my/complete"); // 3秒后跳转
      }, 3000);
    }
  }, 1000);
};

// 格式化时间显示
const formattedTime = computed(() => {
  const minutes = Math.floor(timeLeft.value / 60);
  const seconds = timeLeft.value % 60;
  return `${minutes.toString().padStart(2, "0")}:${seconds
    .toString()
    .padStart(2, "0")}`;
});

// 监听formData变化初始化倒计时
watch(
  () => formData.value?.remainingTime,
  (newVal) => {
    if (newVal) {
      timeLeft.value = newVal;
      startTimer();
    }
  }
);
// 新增返回方法
const handleBack = () => {
  router.go(-1); // 返回上一页
};
// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style>
.submit-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: white;
  padding: 2rem;
  border-radius: 12px;
  width: 400px;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  transform: translateY(-20px);
  animation: slideUp 0.3s ease forwards;
}

.warning-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  color: #ffc107;
  animation: pulse 1.5s infinite;
}

h3 {
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 1.25rem;
}

p {
  color: #666;
  margin-bottom: 1.5rem;
  line-height: 1.5;
}

.button-group {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
}

.confirm-btn {
  background: #1890ff;
  color: white;
}

.confirm-btn:hover {
  background: #40a9ff;
  transform: translateY(-1px);
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #eee;
  color: #333;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  to {
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 移动端适配 */
@media (max-width: 480px) {
  .modal-content {
    width: 90%;
    padding: 1.5rem;
  }

  .button-group {
    flex-direction: column;
  }

  button {
    width: 100%;
  }
}

#viewQuestionView {
  max-width: 1400px !important;
  margin: 0 auto !important;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}
#viewQuestionView .kong {
  height: 10px;
}
/* 新增评论区样式 */
.reply-section {
  margin: 16px 0;
  padding-left: 40px;
}

.action-buttons {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action {
  cursor: pointer;
  color: var(--color-text-2);
  transition: color 0.3s;
}

.action:hover {
  color: var(--color-primary);
}
/* 加载更多按钮样式 */
.load-more {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
/* 添加分数列样式 */
:deep(.arco-table-td[data-col-id="totalScore"]) {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-success-6);
  background-color: var(--color-success-light-1);
}
/* 倒计时样式 */
.countdown {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 20px 0;
  padding: 12px 24px;
  background: #f5f5f5;
  border-radius: 8px;
  display: inline-block;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.countdown.warning {
  color: #ff4d4f;
  background: #fff2f0;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

/* 在现有样式中添加 */
#viewQuestionView {
  /* 保持原有样式 */
}

/* 调整按钮位置 */
.arco-btn {
  margin-top: 16px !important;
}
/* 返回按钮样式 */
.back-btn {
  position: fixed;
  left: 16px;
  top: 110px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--color-bg-2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1000;
}

.back-btn:hover {
  background: var(--color-fill-3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.arrow-icon {
  font-size: 18px;
  color: var(--color-text-1);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .back-btn {
    left: 10px;
    top: 10px;
    width: 36px;
    height: 36px;
  }

  .arrow-icon {
    font-size: 16px;
  }
}
/* 超时提示弹窗样式 */
.timeout-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: white;
  padding: 40px 60px;
  border-radius: 16px;
  text-align: center;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  transform: translateY(-20px);
  animation: slideUp 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

.icon-wrapper {
  margin-bottom: 24px;
}

.clock-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto;
  background: #ff4d4f;
  border-radius: 50%;
  position: relative;
  animation: pulse 1.5s infinite;
}

.clock-icon::before,
.clock-icon::after {
  content: "";
  position: absolute;
  background: white;
}

.clock-icon::before {
  width: 4px;
  height: 24px;
  left: 50%;
  top: 12px;
  transform: translateX(-50%);
}

.clock-icon::after {
  width: 4px;
  height: 16px;
  left: 50%;
  top: 12px;
  transform: translateX(-50%) rotate(90deg);
}

h2 {
  color: #1a1a1a;
  margin-bottom: 12px;
  font-size: 24px;
}

p {
  color: #666;
  margin: 0;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  to {
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .modal-content {
    width: 90%;
    padding: 30px;
  }

  .clock-icon {
    width: 48px;
    height: 48px;
  }
}
</style>
